package dovs.instructions;

/** An <code>ldc</code> instruction with a string parameter. */
public class Ildc_string extends Instruction {
	private String value;

	public Ildc_string(String value) {
		this.value = value;
	}

	public @Override
	String toAsm() {
		StringBuilder sb = new StringBuilder();
		sb.append("ldc \"");
		for (int i = 0; i < value.length(); i++) {
			char c = value.charAt(i);
			if (c >= 512) {
				throw new IllegalArgumentException(
						"Jasmin does not support high unicode characters in strings");
			} else if (c < 32 || c > 126) {
				sb.append("\\");
				sb.append(c / 64);
				sb.append((c / 8) & 7);
				sb.append(c & 7);
			} else if (c == '\"') {
				sb.append("\\\"");
			} else if (c == '\\') {
				sb.append("\\\\");
			} else {
				sb.append(c);
			}
		}
		sb.append("\"");
		return sb.toString();
	}

	public @Override
	int stackChange() {
		return 1;
	}

	public @Override
	Object getArg(int i) {
		switch (i) {
		case 0:
			return value;
		default:
			return null;
		}
	}
}
